<template>
	<view>
		<view>
			<u-notice-bar text="未注册用户首次登录将自动注册帐号" color="#000" bgColor="#FFD84A"></u-notice-bar>
		</view>
		<view class="logo cflex aic wrap">
			<view style="margin-top: 70px;">
				<u-avatar :src="logoSrc" size="70"></u-avatar>
			</view>
			<text class="f16 fbold mt12">欢迎来到发现{{ cityName }}</text>
		</view>

		<view class="login_form dflex cflex" style="padding: 30px;">
			<u-form labelPosition="left" :model="registerModel" ref="registerForm">

				<u-form-item label="手机号" prop="register.phone" ref="phone" labelWidth="70">
					<u--input v-model="registerModel.register.phone" border="bottom" placeholder="请输入手机号码"
						maxlength="11" type="number"></u--input>
				</u-form-item>

				<u-form-item label="验证码" prop="register.code" labelWidth="70" ref="sendCode">
					<u--input v-model="registerModel.register.code" border="bottom" placeholder="请填写验证码" maxlength="4" type="number"></u--input>
					<u-button slot="right" @click="getCode" color="#FFD84A" size="normal" throttleTime="1000" :disabled="disabled1" customStyle="miniWidth:100px;width:100px;">
						<text style="color: #000;">{{ tips }}</text>
					</u-button>
				</u-form-item>

				<view style="margin-top: 20px;">
					<u-button color="#FFD84A" shape="circle" :loading="loginLoading" loadingMode="circle"
						loadingText="登陆中" @click="loginOrRegister" :disabled="checkGetCode">
						<text style="color: #000;">登录/注册</text>
					</u-button>
				</view>

				<view class="user_check mt12 dflex aic" @click="userCheckClick">
					<radio shape="circle" :checked="userCheck" color="#FFD84A" style="transform:scale(0.7);"></radio>
					<u-parse :content="content" :tagStyle="style"></u-parse>
				</view>

			</u-form>

			<u-code ref="uCode" @change="codeChange" seconds="45" @start="disabled1 = true" @end="disabled1 = false">
			</u-code>

			<u-modal 
				:show="showRegister" 
				title="确认同意注册" 
				content="您已阅读并同意《用户服务协议》以及《隐私权政策》？" showCancelButton="true"
				@confirm="ensureRegister" 
				@cancel="closeRegister" 
				@close="closeRegister"
			>
			</u-modal>
			
			<view class="df mt12">
				<u-divider text="更多登录方式"></u-divider>
			</view>
			
			<view class="cflex f14 taligncenter jcc">
				<u-button open-type="getPhoneNumber" 
					type="success" 
					@getphonenumber="decryptPhoneNumber"
					shape="circle"
					icon="weixin-fill"
					customStyle="width: 40px;"
				>
				</u-button>
				<text class="mt12">微信手机号</text>
			</view>

			<view class="mt50">
				<version></version>
			</view>

			<u-toast ref="uToast"></u-toast>

		</view>
	</view>
</template>

<script>
	

	export default {
		data() {
			return {
				logoSrc: uni.getStorageSync('domain') + "/static/avatar.png",
				userCheck: false,
				registerModel: {
					register: {
						phone: '',
						code: ''
					}
				},
				disabled1: '',
				rules: {
					// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
					'register.phone': [{
						type: 'string',
						required: true,
						message: '请输入手机号码',
						trigger: ['change', 'blur']
					}, {
						validator: (rule, value, callback) => {
							return uni.$u.test.mobile(value);
						},
						trigger: ["change", "blur"],
						message: '请输入正确的手机号码',
					}],
					'register.code': [{
						type: 'string',
						max: 4,
						required: true,
						message: '请输入验证码',
						trigger: ["change", "blur"],
					}, {
						validator: (rule, value, callback) => {
							return uni.$u.test.code(value, 4);
						},
						trigger: ["change", "blur"],
						message: '请输入4位数字验证码',
					}]
				},
				tips: '',
				content: `<p>我已阅读并同意<a href=\"\/pages\/about\/service\">《用户服务协议》</a>以及<a href=\"\/pages\/about\/privacy\">《隐私权政策》</a></p>`,
				style: {
					// 字符串的形式
					p: 'font-size:12px',
					a: 'font-size:12px;color:#333;text-decoration: underline;'
				},
				showRegister: false,
				checkGetCode: true,
				loginLoading: false,
				errMsg:'',
				iv:'',
				encryptedData:'',
				code:'',
				cityName : uni.getStorageSync('cityName'),
				from_topic : false,
				from_topic_id : ''
			}
		},
		onLoad: function(e) {
			//初始列表
			uni.showLoading({
				title: "加载中...."
			})
			console.log(e)
			//表明用户来源帖子，方便返回继续操作
			if(e.from_topic > 0) {
				this.from_topic = true
				this.from_topic_id = e.from_topic
			}
			//提前获取code，方便登录
			this.getWxCode()
			//判断登录
			uni.request({
				url: uni.getStorageSync('domain') + '/api/v1/user',
				method: 'get',
				header: {
					'Accept': 'application/json',
					'Authorization': 'Bearer ' + uni.getStorageSync('access_member_info').access_token
				},
				success: (res) => {
					if (res.statusCode == 401) {
						uni.removeStorageSync("access_member_info")
					}
					if (res.statusCode == 200 || res.statusCode == 201) {
						uni.navigateTo({
							url: "/pages/member/member"
						});
					}
					uni.hideLoading();
				},
				fail: (res) => {}
			})
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.registerForm.setRules(this.rules)
		},
		methods: {
			show_toast(mes) {
				this.$refs.uToast.show({
					message: mes,
				})
			},
			ensureRegister() {
				this.showRegister = false
				this.userCheck = true
				this.loginOrRegister()
			},
			closeRegister() {
				this.showRegister = false
			},
			userCheckClick() {
				this.userCheck = !this.userCheck;
				console.log(this.userCheck)
			},
			codeChange(text) {
				this.tips = text;
			},
			getCode() {
				if (this.$refs.uCode.canGetCode) {
					uni.showLoading({
						title: '获取验证码...',
						mask: true
					});
					uni.request({
						url: uni.getStorageSync('domain') + '/api/v1/verificationCodes',
						method: 'POST',
						data: {
							phone: this.registerModel.register.phone
						},
						success: (res) => {
							if (res.statusCode != 201) {
								// console.log(res);
								this.show_toast(res.data.message);
							} else {
								// console.log(res.data);
								this.checkGetCode = false;
								uni.setStorageSync("code_key", res.data.key);
								// 通知验证码组件内部开始倒计时
								this.$refs.uCode.start();
								// console.log(uni.getStorageSync("code_key"));
							}
							uni.hideLoading();
						},
						fail: (res) => {}
					})
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},
			loginOrRegister() {
				if (this.userCheck == false) {
					this.showRegister = true
				} else {
					this.$refs.registerForm.validate().then(res => {
						// console.log("注册流程开始")
						uni.request({
							url: uni.getStorageSync('domain') + '/api/v1/users',
							method: 'POST',
							data: {
								verification_key: uni.getStorageSync("code_key"),
								verification_code: this.registerModel.register.code
							},
							success: (res) => {
								if (res.statusCode != 201) {
									// console.log(res);
									this.show_toast(res.data.message)
									// uni.$u.toast(res.data.message);
								} else {
									// console.log(res.data);
									uni.setStorageSync("access_member_info", res.data);
									uni.setStorageSync("login_type", "phone");
									this.show_toast('登录成功')
									this.loginLoading = true
									setTimeout(() => {
										if(this.from_topic) {											
											uni.navigateTo({
												url: "/pages/article/article2?TopicId=" + this.from_topic_id,
											})
										} else {
											uni.redirectTo({
												url: '/pages/index/index'
											})
										}
									}, 1500)
								}
							},
							fail: (res) => {}
						})
					}).catch(errors => {
						console.log(errors);
						uni.$u.toast('请正确填写表单内容')
					})
				}
			},
			getWxCode() {
				uni.login({
					provider:'weixin',
					success: (res) => {
						this.code = res.code
					}
				})
			},
			decryptPhoneNumber(e) {
				this.userCheck = true
				this.errMsg = e.detail.errMsg
				this.iv = e.detail.iv
				this.encryptedData  = e.detail.encryptedData
				// console.log('e.detail.encryptedData', e.detail.encryptedData)
				// console.log('this.code', this.code)
				//用户取消这个值就获取不到，就不要发请求到服务器了
				if(e.detail.encryptedData && this.code != '') {
					//加一个延时，防止code没获取到
					setTimeout(()=>{
						uni.request({
							url: uni.getStorageSync('domain') + '/api/v1/user/miniphonenumber',
							method: 'POST',
							data: {
								errMsg:this.errMsg,
								iv: this.iv,
								encryptedData : this.encryptedData,
								code : this.code
							},
							success: (res) => {
								// console.log('this.code', this.code)
								if (res.statusCode != 201) {
									// console.log(res);
									this.show_toast(res.data.message)
									// uni.$u.toast(res.data.message);
								} else {
									// console.log(res.data);
									uni.setStorageSync("access_member_info", res.data);
									uni.setStorageSync("login_type", "phone");
									this.show_toast('登录成功')
									this.loginLoading = true
									setTimeout(() => {
										if(this.from_topic) {											
											uni.navigateTo({
												url: "/pages/article/article2?TopicId=" + this.from_topic_id,
											})
										} else {
											uni.redirectTo({
												url: '/pages/index/index'
											})
										}
									}, 1500)
								}
							},
							fail: (res) => {}
						})
					},1000)
				}
			}
		}
	}
</script>

<style>

</style>
